#!/usr/bin/python

#Ganna Raboshchuk {ganna.raboshchuk@upc.edu}
#21.10.2013
#UPC, Barcelona

#Merge the output labels from recognizer.
#--------------------------------------------------------------------------

import sys
import linecache

START_TIME = 0
END_TIME = 1
CLASS = 2

resultsFolder = sys.argv[1]
p = sys.argv[2]

#resultFile = resultsFolder + '/out_' + str(p) + '.mmf'
resultFile = resultsFolder + '/out_smooth_' + str(p) + '.mmf'
labelling = open(resultFile, 'r')

outputFile = resultsFolder + '/out_merged_' + str(p) + '.mmf'
output = open(outputFile, 'w')
output.write('#!MLF!#\n')

mergedLabelling = []
filename = ''

for line in labelling:
    if not line[0].isdigit():        
        if (line != '#!MLF!#\n'):
            if (line == '.\n'):
                if len(mergedLabelling) != 0:        
                    #Merge
                    lastLabel = '' #the very first label
                    lastIndex = 0 #the first index of the label with the same class in a row
        
                    i = 0
                    while i < len(mergedLabelling): 
                        if lastLabel == mergedLabelling[i][CLASS]:
                            mergedLabelling[lastIndex][END_TIME] = mergedLabelling[i][END_TIME]
                            mergedLabelling.remove(mergedLabelling[i])
                        else:
                            lastIndex = i
                            lastLabel = mergedLabelling[i][CLASS]
                            i += 1
                            
                    #Output results to file
                    output.write(filename) #output the name of the testing file
                    for i in range(len(mergedLabelling)):
                        output.write(' '.join(mergedLabelling[i]) + '\n')
                    output.write('.\n')
                    mergedLabelling = []
            else:
                filename = line
            
    else: #reading in labelling
        labels = line.split()
        mergedLabelling.append(labels[0:3])        

labelling.close()
output.close()


            

    


    
        
